<template>
	<div class="container">
		<h4>子组件收到的值</h4>
		<input type="text" v-model="sendToParentMessage" />
		<button @click="sendToParent">send</button>
		<input type="text" v-model="sendToBrotherMessage" />
		<button @click="sendToBrother">send</button>
		<ul>
			<li v-for="(message, index) in messages" :key="message + index">
				{{ message }}
			</li>
		</ul>
	</div>
</template>

<script>
import { EventBus } from '../eventBus';

export default {
	props: {
		parentMessage: String,
	},

	data() {
		return {
			messages: [],
			sendToParentMessage: '',
			sendToBrotherMessage: '',
		};
	},
	methods: {
		sendToParent() {
			this.$emit('messageFromChild', this.sendToParentMessage);
			this.sendToParentMessage = '';
		},

		// 想兄弟组件传值
		sendToBrother() {
			EventBus.$emit('brother', this.sendToBrotherMessage);
			this.sendToBrotherMessage = '';
		},
	},

	// 监听父组件传过来的值，并存储在消息盒子中
	watch: {
		parentMessage: function (newVal) {
			newVal.length > 0 && this.messages.push(newVal.trim());
		},
	},

	// 清除watch监听
	unmounted() {
		this.parentMessage;
	},
};
</script>

<style scoped>
.container {
	width: 200px;
	height: 200px;
	background-color: aqua;
}
</style>
